About 2458 letters
About 12 minutes
In CSS, the margin
and padding
properties are used to set the outer and inner spacing of elements, respectively.
/* Margin */
margin: A; /* Sets A for all four sides */
margin: A B; /* Sets A for top & bottom, B for left & right */
margin: A B C D; /* Sets top=A, right=B, bottom=C, left=D */
margin-top: A; /* Top margin */
margin-bottom: A; /* Bottom margin */
margin-left: A; /* Left margin */
margin-right: A; /* Right margin */
/* Padding */
padding: A; /* Sets A for all four sides */
padding: A B; /* Sets A for top & bottom, B for left & right */
padding: A B C D; /* Sets top=A, right=B, bottom=C, left=D */
padding-top: A; /* Top padding */
padding-bottom: A; /* Bottom padding */
padding-left: A; /* Left padding */
padding-right: A; /* Right padding */
Example:
<div style="background-color:green;">
<div style="margin: 30px; padding: 30px; background-color:#212121; color:cyan;">
margin: 30px; <br/>
padding: 30px; <br/>
</div>
</div>
Padding & Marginmargin: 30px;
padding: 30px;
In this example, it may appear that only the left and right margins of the inner div
are effective, while the top and bottom margins seem to have no effect.
In fact, the vertical margins have “leaked” outside the outer div
.
This behavior is known as Margin Collapse, where the vertical margins of nested elements are combined, and only the largest one takes effect.
You can prevent margin collapse by setting the outer container’s overflow
property to a value other than visible
, for example:
<div style="background-color:green; overflow:hidden;">
<div style="margin: 30px; padding: 30px; border: 3px solid red; background-color:#212121; color:cyan;">
margin: 30px; <br/>
padding: 30px; <br/>
border: 3px solid red; <br/>
</div>
</div>
Prevent Margin Collapsemargin: 30px;
padding: 30px;
border: 3px solid red;
Created in 5/20/2025
Updated in 5/20/2025